// Copyright 2022 a.o.smith ALL Rights Reserved
package com.liuxinlong.modules.patent.service.impl;

import com.liuxinlong.common.AosException;
import com.liuxinlong.common.SnowFlake;
import com.liuxinlong.constant.ThreadLocalConstants;
import com.liuxinlong.constant.TimeFormatConstants;
import com.liuxinlong.enums.DifficultyStatusEnum;
import com.liuxinlong.enums.PatentClassTypeEnum;
import com.liuxinlong.enums.PatentRiskTypeEnum;
import com.liuxinlong.enums.ProjectLevelEnum;
import com.liuxinlong.enums.ProjectPatentStageEnum;
import com.liuxinlong.enums.ReturnCodes;
import com.liuxinlong.enums.WorkflowTypeEnum;
import com.liuxinlong.modules.common.entity.WorkflowDto;
import com.liuxinlong.modules.common.entity.WorkflowRecordDto;
import com.liuxinlong.modules.common.service.WorkFlowService;
import com.liuxinlong.modules.dao.PatentDepartmentDao;
import com.liuxinlong.modules.dao.PatentDepartmentSpecialDao;
import com.liuxinlong.modules.dao.PatentProposalDao;
import com.liuxinlong.modules.dao.PatentRiskDao;
import com.liuxinlong.modules.dao.PatentRiskProcessDao;
import com.liuxinlong.modules.dao.ProjectDao;
import com.liuxinlong.modules.dao.ProjectPatentExpandDao;
import com.liuxinlong.modules.dao.RoleDao;
import com.liuxinlong.modules.dao.UserDao;
import com.liuxinlong.modules.dao.UserRoleRelationDao;
import com.liuxinlong.modules.dao.WorkFlowDao;
import com.liuxinlong.modules.dao.WorkFlowNodeConfigDao;
import com.liuxinlong.modules.dao.WorkFlowNodeRecordDao;
import com.liuxinlong.modules.entity.PatentDepartment;
import com.liuxinlong.modules.entity.PatentDepartmentSpecial;
import com.liuxinlong.modules.entity.PatentProposal;
import com.liuxinlong.modules.entity.PatentRisk;
import com.liuxinlong.modules.entity.PatentRiskProcess;
import com.liuxinlong.modules.entity.Project;
import com.liuxinlong.modules.entity.ProjectPatentExpand;
import com.liuxinlong.modules.entity.User;
import com.liuxinlong.modules.entity.UserRole;
import com.liuxinlong.modules.entity.UserRoleRelation;
import com.liuxinlong.modules.entity.WorkFlowNodeConfig;
import com.liuxinlong.modules.patent.dto.PatentProjectDto;
import com.liuxinlong.modules.patent.service.PatentRiskProcessService;
import com.liuxinlong.modules.patent.service.PatentRiskService;
import com.liuxinlong.modules.system.service.FileManageService;
import com.liuxinlong.utils.IPUtils;
import com.liuxinlong.utils.ObjectUtils;
import com.liuxinlong.utils.PdfUtils;
import com.liuxinlong.utils.ThreadlocalUtils;
import com.liuxinlong.utils.TimeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 专利风险管控实现类
 *
 * @author liuxinlong@hotwater.com.cn
 * @version 1.0.0
 * @since 2024-03-18
 */
@Service
@Slf4j
public class PatentRiskServiceImpl implements PatentRiskService {
    @Autowired
    private UserDao userDao;

    @Autowired
    private PatentRiskDao patentRiskDao;

    @Autowired
    private PatentProposalDao patentProposalDao;

    @Autowired
    private PatentDepartmentDao patentDepartmentDao;

    @Autowired
    private ProjectPatentExpandDao projectPatentExpandDao;

    @Autowired
    private WorkFlowService workFlowService;

    @Autowired
    private FileManageService fileManageService;

    @Autowired
    private PatentDepartmentSpecialDao patentDepartmentSpecialDao;

    @Autowired
    private UserRoleRelationDao userRoleRelationDao;

    @Autowired
    private RoleDao roleDao;

    @Autowired
    private PatentRiskProcessDao patentRiskProcessDao;

    @Autowired
    private WorkFlowDao workFlowDao;

    @Autowired
    private WorkFlowNodeRecordDao workFlowNodeRecordDao;

    @Autowired
    private WorkFlowNodeConfigDao workFlowNodeConfigDao;

    @Autowired
    private PatentRiskProcessService patentRiskProcessService;

    @Autowired
    private ProjectDao projectDao;

    @Override
    public List<Map<String, Object>> pagePatentProjectInfo(Map<String, Object> queryParam) {
        User currentUser = (User) ThreadlocalUtils.getCache(ThreadLocalConstants.USER_INFO);
        String userId = currentUser.getId();
        queryParam.put("userId", userId);
        List<PatentDepartment> departmentList = patentDepartmentDao.getDepartmentByManager(userId);
        if (!ObjectUtils.isEmpty(departmentList)) {
            List<String> depList = departmentList.stream().map(PatentDepartment::getId).collect(Collectors.toList());
            queryParam.put("manageDepartment", depList);
            queryParam.put("userId", null);
        }
        List<PatentDepartment> dutyDepartmentList = patentDepartmentDao.getDepartmentByDutyUser(userId);
        if (!dutyDepartmentList.isEmpty()) {
            if (queryParam.containsKey("manageDepartment")) {
                List<String> depList = (List<String>) queryParam.get("manageDepartment");
                List<String> allList = new ArrayList<>();
                allList.addAll(depList);
                allList.addAll(dutyDepartmentList.stream().map(PatentDepartment::getId).collect(Collectors.toList()));
                queryParam.put("manageDepartment", allList);
            } else {
                List<String> allList = dutyDepartmentList.stream().map(PatentDepartment::getId).collect(Collectors.toList());
                queryParam.put("manageDepartment", allList);
            }
            queryParam.put("userId", null);
        }
        PatentDepartmentSpecial special = patentDepartmentSpecialDao.getDepartmentSpecialById(userId);
        if (!ObjectUtils.isEmpty(special)) {
            if (queryParam.containsKey("manageDepartment")) {
                List<String> depList = (List<String>) queryParam.get("manageDepartment");
                List<String> allList = new ArrayList<>();
                allList.addAll(depList);
                allList.addAll(Arrays.asList(special.getBranch().split(",")));
                queryParam.put("manageDepartment", allList);
            } else {
                List<String> allList = Arrays.asList(special.getBranch().split(","));
                queryParam.put("manageDepartment", allList);
            }
            queryParam.put("userId", null);
        }
//        dataMap.put("departmentPermission", !ObjectUtils.isEmpty(departmentList) || !ObjectUtils.isEmpty(special));
        List<UserRoleRelation> userRoleRelationList = userRoleRelationDao.queryRelationByUserId(currentUser.getId());
        UserRole highRole = roleDao.getRoleBySn("J020");
        List<UserRoleRelation> existHighList;
        if (ObjectUtils.isEmpty(highRole)) {
            existHighList = new ArrayList<>();
        } else {
            existHighList = userRoleRelationList.stream().filter(relation -> StringUtils.equals(relation.getRoleId(), highRole.getId())).collect(Collectors.toList());
        }
//        dataMap.put("highPermission", !existHighList.isEmpty());
        // 专利经理
        UserRole manageRole = roleDao.getRoleBySn("J025");
        List<UserRoleRelation> existList;
        if (ObjectUtils.isEmpty(manageRole)) {
            existList = new ArrayList<>();
        } else {
            existList = userRoleRelationList.stream().filter(relation -> StringUtils.equals(relation.getRoleId(), manageRole.getId())).collect(Collectors.toList());
        }
//        dataMap.put("managePermission", !existList.isEmpty());

        UserRole superManageRole = roleDao.getRoleBySn("J007");
        List<UserRoleRelation> existSuperList;
        if (ObjectUtils.isEmpty(superManageRole)) {
            existSuperList = new ArrayList<>();
        } else {
            existSuperList = userRoleRelationList.stream().filter(relation -> StringUtils.equals(relation.getRoleId(), superManageRole.getId())).collect(Collectors.toList());
        }
        boolean superPermission = !existSuperList.isEmpty();
//        dataMap.put("superPermission", !existSuperList.isEmpty());
        if (!existHighList.isEmpty() ||
                !existList.isEmpty() ||
                !existSuperList.isEmpty()) {
            queryParam.put("manageDepartment", null);
            queryParam.put("userId", null);
        }

        List<PatentProjectDto> originList = projectPatentExpandDao.pagePatentProjectList(queryParam);
        return completeResult(originList, (int) queryParam.get("startNum"),userId,superPermission);
    }

    @Override
    public int countPatentProject(Map<String, Object> queryParam) {
        return projectPatentExpandDao.getPatentProjectCount(queryParam);
    }

    @Override
    public List<Map<String, Object>> pagePatentRiskInfo(Map<String, Object> queryParam) {
        List<PatentRisk> originList = patentRiskDao.pagePatentRiskList(queryParam);
        return completeRiskResult(originList, (int) queryParam.get("startNum"));
    }

    @Override
    public int countPatentRisk(Map<String, Object> queryParam) {
        return patentRiskDao.getPatentRiskCount(queryParam);
    }

    @Override
    public void addPatentRiskInfo(PatentRisk patentRisk) {
        User currentUser = (User) ThreadlocalUtils.getCache(ThreadLocalConstants.USER_INFO);
        String currentTime = TimeUtils.getDate(TimeFormatConstants.YYYY_MM_DD_HH_MM_SS);
        patentRisk.setId(SnowFlake.nextIdStr());
        patentRisk.setStatus(1);
        patentRisk.setCreateUser(currentUser.getId());
        patentRisk.setCreateTime(currentTime);
        patentRiskDao.insert(patentRisk);
        fileManageService.updateBusinessFile(patentRisk.getPicture(), patentRisk.getId());
    }

    @Override
    public void updatePatentRiskInfo(PatentRisk patentRisk) {
        PatentRisk oldInfo = patentRiskDao.selectById(patentRisk.getId());
        if (ObjectUtils.isEmpty(oldInfo)) {
            throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "专利风险点不存在！");
        }
        User currentUser = (User) ThreadlocalUtils.getCache(ThreadLocalConstants.USER_INFO);
        String currentTime = TimeUtils.getDate(TimeFormatConstants.YYYY_MM_DD_HH_MM_SS);
        patentRisk.setStatus(oldInfo.getStatus());
        patentRisk.setProcessNode(oldInfo.getProcessNode());
        patentRisk.setUpdateUser(currentUser.getId());
        patentRisk.setUpdateTime(currentTime);
        patentRisk.setSearchRecord(oldInfo.getSearchRecord());
//        patentRisk.setPlanSourceInfo(oldInfo.getPlanSourceInfo());
        patentRiskDao.updateById(patentRisk);
        List<String> pictureList = new ArrayList<>();
        if (!StringUtils.isEmpty(patentRisk.getPicture())) {
            pictureList.addAll(Arrays.asList(patentRisk.getPicture().split(",")));
        }
        if (!StringUtils.isEmpty(patentRisk.getSearchRecord())) {
            pictureList.add(patentRisk.getSearchRecord());
        }
        fileManageService.updateBusinessFile(StringUtils.strip(pictureList.toString(), "[]").replaceAll(" +", ""), patentRisk.getId());
    }

    @Override
    public void deletePatentRiskInfo(String id) {
        Map<String, Object> queryParam = new HashMap<>();
        queryParam.put("riskId", id);
        int proposalNum = patentProposalDao.getPatentProposalCount(queryParam);
        if (proposalNum > 0) {
            throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "存在关联风险专利！");
        }
        patentRiskDao.deleteById(id);
    }

    @Override
    public void updatePatentRiskStatus(String id, int type, int targetStatus) {
        User currentUser = (User) ThreadlocalUtils.getCache(ThreadLocalConstants.USER_INFO);
        String currentTime = TimeUtils.getDate(TimeFormatConstants.YYYY_MM_DD_HH_MM_SS);
        ProjectPatentExpand expand = projectPatentExpandDao.selectById(id);
        if (ObjectUtils.isEmpty(expand)) {
            throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "修改失败，项目信息不存在！");
        }
        expand.setUpdateUser(currentUser.getId());
        expand.setUpdateTime(currentTime);
        if (type == 1) {
            expand.setRiskStatus(targetStatus);
        } else if (type == 2) {
            expand.setMonitor(targetStatus);
        } else {
            throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "修改失败!");
        }
        projectPatentExpandDao.updateById(expand);
    }

    @Override
    @Transactional
    public void startPatentRiskProcess(String id, int type, String dataString, List<Map<String, Object>> changeList) {
//        if (type == 1) {
//            String currentTime = TimeUtils.getDate(TimeFormatConstants.YYYY_MM_DD_HH_MM_SS);
//            User currentUser = (User) ThreadlocalUtils.getCache(ThreadLocalConstants.USER_INFO);
//            Map<String, PatentRisk> riskMap = patentRiskDao.getProjectPatentRiskMap(id);
//            List<PatentRisk> updateList = new ArrayList<>();
//            for (Map<String, Object> item : changeList) {
//                String riskId = (String) item.get("id");
//                if (riskMap.containsKey(riskId)) {
//                    PatentRisk patentRisk = riskMap.get(riskId);
//                    patentRisk.setPlanSourceInfo(item.containsKey("expand") ?
//                            (StringUtils.equals((CharSequence) item.get("expand"), "-") ? "" : (String) item.get("expand")) : "");
//                    patentRisk.setUpdateTime(currentTime);
//                    patentRisk.setUpdateUser(currentUser.getId());
//                    updateList.add(patentRisk);
//                }
//            }
//            if (updateList.size() > 0) {
//                patentRiskDao.updateBatchById(updateList);
//            }
//        }
        workFlowService.startWorkflow(id, type == 1 ? WorkflowTypeEnum.PATENT_INVESTIGATION.getValue() :
                WorkflowTypeEnum.PATENT_RISK_ANALYSIS.getValue(), dataString);
        if (type == 2) {
            List<PatentRisk> patentRiskList = patentRiskDao.getAvailablePatentRiskList(id);
            PatentRiskProcess currentSortProcess = patentRiskProcessDao.getCurrentSort(id);
            List<PatentRisk> updateList = new ArrayList<>(patentRiskList.size());
            for (PatentRisk risk : patentRiskList) {
                risk.setProcessNode(currentSortProcess.getSortNum());
                updateList.add(risk);
            }
            if (!updateList.isEmpty()) {
                patentRiskDao.updateBatchById(updateList);
            }
        }
    }

    @Override
    @Transactional
    public void updateRiskSearchRecord(String id, String fileId) {
        User currentUser = (User) ThreadlocalUtils.getCache(ThreadLocalConstants.USER_INFO);
        String currentTime = TimeUtils.getDate(TimeFormatConstants.YYYY_MM_DD_HH_MM_SS);
        PatentRisk patentRisk = patentRiskDao.selectById(id);
        if (ObjectUtils.isEmpty(patentRisk)) {
            throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "修改失败，设计差异点不存在！");
        }
        List<String> pictureList = new ArrayList<>();
        if (!StringUtils.isEmpty(patentRisk.getPicture())) {
            pictureList.addAll(Arrays.asList(patentRisk.getPicture().split(",")));
        }
        pictureList.add(fileId);
        fileManageService.updateBusinessFile(StringUtils.strip(pictureList.toString(), "[]").replaceAll(" +", ""), id);
        patentRisk.setSearchRecord(fileId);
        patentRisk.setUpdateUser(currentUser.getId());
        patentRisk.setUpdateTime(currentTime);
        patentRiskDao.updateById(patentRisk);
    }

    @Override
    public Map<String, Object> queryProjectCompleteReport(String id) {
        Map<String, Map<String, String>> userMap = userDao.getUserMap();
        Map<String, Object> query = new HashMap<>();
        query.put("startNum", 0);
        query.put("pageSize", 10000);
        query.put("projectId", id);
        // 设计差异点数据列表
        List<PatentRisk> riskList = patentRiskDao.pagePatentRiskList(query);
        List<Map<String, Object>> riskDataList = new ArrayList<>(riskList.size());
        int riskSort = 1;
        for (PatentRisk risk : riskList) {
            Map<String, Object> item = ObjectUtils.object2Map(risk);
            item.put("sort", riskSort);
            Map<String, Object> fileMap = fileManageService.queryFileManageInfos(risk.getId());
            if (fileMap.containsKey("39")) {
                item.put("pictureUrl", fileMap.get("39"));
            }
            riskDataList.add(item);
            riskSort++;
        }
        // 相关专利数据列表
        List<PatentProposal> proposalList = patentProposalDao.pagePatentProposalList(query);
        List<Map<String, Object>> proposalDataList = new ArrayList<>(proposalList.size());
        int proposalSort = 1;
        for (PatentProposal proposal : proposalList) {
            Map<String, Object> item = ObjectUtils.object2Map(proposal);
            item.put("sort", proposalSort);
            item.put("classTypeName", PatentClassTypeEnum.getNameByValue(proposal.getClassType()));
            item.put("statusName", proposal.getStatus());
            item.put("riskTypeName", proposal.getRiskType() == 1 ? "侵权" : "不侵权");
            item.put("levelName", proposal.getLevel() == 1 ? "高风险" : proposal.getLevel() == 2 ? "低风险" : proposal.getLevel() == 3 ? "无风险" : "未定义");
            proposalDataList.add(item);
            proposalSort++;
        }
        // 风险管控记录数据列表
        List<Map<String, Object>> processList = patentRiskProcessService.pagePatentRiskProcessInfo(query);
        // 签批记录数据列表
        query.put("businessId", id);
        query.put("businessType", null);
        List<WorkflowDto> workFlowList = workFlowDao.getBusinessWorkflowList(id);
        List<WorkflowRecordDto> workFlowRecordList = workFlowNodeRecordDao.getBusinessWorkflowRecord(query);
        List<String> configIdList = workFlowRecordList.stream().map(WorkflowRecordDto::getFlowConfigId).collect(Collectors.toList());
        Map<String, WorkFlowNodeConfig> nodeConfigMap = new HashMap<>();
        if (!configIdList.isEmpty()) {
            List<WorkFlowNodeConfig> nodeConfigList = workFlowNodeConfigDao.getWorkflowNodeConfigByList(configIdList);
            for (WorkFlowNodeConfig nodeConfig : nodeConfigList) {
                nodeConfigMap.put(nodeConfig.getConfigId() + "-" + nodeConfig.getSortNum(), nodeConfig);
            }
        }
        List<Map<String, Object>> workflowDataList = new ArrayList<>(workFlowRecordList.size());
        Map<String,List<Map<String, Object>>> workflowDetailMap = new HashMap<>();

        for (WorkflowRecordDto record : workFlowRecordList) {
            Map<String, Object> item = ObjectUtils.object2Map(record);
            String nodeKey = record.getFlowConfigId() + "-" + record.getNode();
//            item.put("sort", workflowSort);
//            item.put("flowStatusName", record.getFlowStatus() == 1 ? "进行中" : record.getFlowStatus() == 2 ? "已完成" : "废止");
            item.put("dealUserName", userMap.containsKey(record.getDealUser()) ? userMap.get(record.getDealUser()).get("name") : "");
//            item.put("flowTypeName", WorkflowTypeEnum.getNameByValue(record.getBusinessType()));
            //            item.put("dealTypeName", !ObjectUtils.isEmpty(endNodeConfig) && record.getNode() == endNodeConfig.getSortNum() ? "流程结束" : record.getNode() == 1 ? "流程发起" : "审核");
            item.put("resultName", record.getResult() == 1 ? "通过" : record.getResult() == 2 ? "拒绝" : record.getResult() == 3 ? "未处理" : record.getResult() == 4 ? "自动处理通过（他人已办）" : "未处理");
            if (nodeConfigMap.containsKey(nodeKey)) {
                WorkFlowNodeConfig nodeConfig = nodeConfigMap.get(nodeKey);
                item.put("nodeName", nodeConfig.getContent());
                item.put("dealTypeName", nodeConfig.getNodeType() == 1 ? "流程发起" : nodeConfig.getNodeType() == 2 ? "流程结束" : "审核");
            }
            String workflowId = record.getWorkflowId();
            List<Map<String, Object>> detailList = workflowDetailMap.containsKey(workflowId) ? workflowDetailMap.get(workflowId) : new ArrayList<>();
            int sort = detailList.size() + 1;
            item.put("sort", sort);
                    detailList.add(item);
            workflowDetailMap.put(workflowId,detailList);
        }
        int workflowSort = 1;
        for (WorkflowDto workflow : workFlowList) {
            Map<String, Object> item = ObjectUtils.object2Map(workflow);
            item.put("flowTypeName", WorkflowTypeEnum.getNameByValue(workflow.getBusinessType()));
            item.put("statusName", workflow.getStatus() == 1 ? "进行中" : workflow.getStatus() == 2 ? "已完成" : "废止");
            item.put("sort",workflowSort);
            item.put("detailList",workflowDetailMap.containsKey(workflow.getId()) ? workflowDetailMap.get(workflow.getId()) : new ArrayList<>());
            workflowDataList.add(item);
            workflowSort++;
        }

        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("riskList", riskDataList);
        dataMap.put("proposalList", proposalDataList);
        dataMap.put("processList", processList);
        dataMap.put("workflowList", workflowDataList);
        return dataMap;
    }

    @Override
    public void exportProjectCompleteReport(String id, HttpServletResponse response) {
        Map<String, Map<String, String>> userMap = userDao.getUserMap();
        Map<String, Object> query = new HashMap<>();
        query.put("startNum", 0);
        query.put("pageSize", 10000);
        query.put("projectId", id);

        Project project = projectDao.selectById(id);
        Map<String,Object> map = ObjectUtils.object2Map(project);
        map.put("projectName",project.getProjectName());
        map.put("projectLevelName",ProjectLevelEnum.getNameByValue(project.getProjectLevel()));
        map.put("projectTypeName",project.getProjectType() == 1 ? "预研项目" :  project.getProjectType() == 2 ?
                "新品开发" : project.getProjectType() == 3 ? "其他": "未知");
        map.put("statusName", project.getStatus() == 1 ? "进行中" :  project.getStatus() == 2 ?
                "已完成" : project.getStatus() == 3 ? "pending": "未知");
        PatentDepartment patentDepartment = patentDepartmentDao.selectById(project.getDepartment());
        map.put("projectDepartmentName",patentDepartment.getName());
        map.put("projectManagerName",userMap.get(project.getProjectManager()).get("name"));
        // 设计差异点数据列表
        List<PatentRisk> riskList = patentRiskDao.pagePatentRiskList(query);
        List<Map<String, Object>> riskDataList = new ArrayList<>(riskList.size());
        int riskSort = 1;
        for (PatentRisk risk : riskList) {
            Map<String, Object> item = ObjectUtils.object2Map(risk);
            item.put("sort", riskSort);
            Map<String, Object> fileMap = fileManageService.queryFileManageInfos(risk.getId());
            if (fileMap.containsKey("39")) {
                item.put("pictureUrl", fileMap.get("39"));
            }
            riskDataList.add(item);
            riskSort++;
        }
        map.put("riskDataList",riskDataList);
        // 风险管控记录数据列表
        List<Map<String, Object>> processList = patentRiskProcessService.pagePatentRiskProcessInfo(query);
        map.put("processList",processList);
        // 签批记录数据列表
        query.put("businessId", id);
        query.put("businessType", null);
        List<WorkflowDto> workFlowList = workFlowDao.getBusinessWorkflowList(id);
        List<WorkflowRecordDto> workFlowRecordList = workFlowNodeRecordDao.getBusinessWorkflowRecord(query);
        List<String> configIdList = workFlowRecordList.stream().map(WorkflowRecordDto::getFlowConfigId).collect(Collectors.toList());
        Map<String, WorkFlowNodeConfig> nodeConfigMap = new HashMap<>();
        if (!configIdList.isEmpty()) {
            List<WorkFlowNodeConfig> nodeConfigList = workFlowNodeConfigDao.getWorkflowNodeConfigByList(configIdList);
            for (WorkFlowNodeConfig nodeConfig : nodeConfigList) {
                nodeConfigMap.put(nodeConfig.getConfigId() + "-" + nodeConfig.getSortNum(), nodeConfig);
            }
        }

        List<Map<String, Object>> workflowDataList = new ArrayList<>(workFlowRecordList.size());
        Map<String,List<Map<String, Object>>> workflowDetailMap = new HashMap<>();

        for (WorkflowRecordDto record : workFlowRecordList) {
            Map<String, Object> item = ObjectUtils.object2Map(record);
            String nodeKey = record.getFlowConfigId() + "-" + record.getNode();
//            item.put("sort", workflowSort);
//            item.put("flowStatusName", record.getFlowStatus() == 1 ? "进行中" : record.getFlowStatus() == 2 ? "已完成" : "废止");
            item.put("dealUserName", userMap.containsKey(record.getDealUser()) ? userMap.get(record.getDealUser()).get("name") : "");
//            item.put("flowTypeName", WorkflowTypeEnum.getNameByValue(record.getBusinessType()));
            //            item.put("dealTypeName", !ObjectUtils.isEmpty(endNodeConfig) && record.getNode() == endNodeConfig.getSortNum() ? "流程结束" : record.getNode() == 1 ? "流程发起" : "审核");
            item.put("resultName", record.getResult() == 1 ? "通过" : record.getResult() == 2 ? "拒绝" : record.getResult() == 3 ? "未处理" : record.getResult() == 4 ? "自动处理通过（他人已办）" : "未处理");
            if (nodeConfigMap.containsKey(nodeKey)) {
                WorkFlowNodeConfig nodeConfig = nodeConfigMap.get(nodeKey);
                item.put("nodeName", nodeConfig.getContent());
                item.put("dealTypeName", nodeConfig.getNodeType() == 1 ? "流程发起" : nodeConfig.getNodeType() == 2 ? "流程结束" : "审核");
            }
            String workflowId = record.getWorkflowId();
            List<Map<String, Object>> detailList = workflowDetailMap.containsKey(workflowId) ? workflowDetailMap.get(workflowId) : new ArrayList<>();
            int sort = detailList.size() + 1;
            item.put("sort", sort);
            detailList.add(item);
            workflowDetailMap.put(workflowId,detailList);
        }
        int workflowSort = 1;
        for (WorkflowDto workflow : workFlowList) {
            Map<String, Object> item = ObjectUtils.object2Map(workflow);
            item.put("flowTypeName", WorkflowTypeEnum.getNameByValue(workflow.getBusinessType()));
            item.put("statusName", workflow.getStatus() == 1 ? "进行中" : workflow.getStatus() == 2 ? "已完成" : "废止");
            item.put("operateUser",userMap.get(workflow.getCreateUser()).get("name"));
            item.put("sort",workflowSort);
            item.put("detailList",workflowDetailMap.containsKey(workflow.getId()) ? workflowDetailMap.get(workflow.getId()) : new ArrayList<>());
            workflowDataList.add(item);
            workflowSort++;
        }
        map.put("workflowDataList",workflowDataList);
        User user = (User) ThreadlocalUtils.getCache(ThreadLocalConstants.USER_INFO);
        map.put("operateUser",user.getName() + "-" + user.getSn());
        map.put("operateTime",TimeUtils.getDate(TimeFormatConstants.YYYY_MM_DD_HH_MM_SS));
        PdfUtils.generatePDFDoc("project_complete_report.pdf", response, map,2);

    }

    @Override
    public void updateProjectAssist(String id, String assistId) {
        ProjectPatentExpand projectPatentExpand = projectPatentExpandDao.selectById(id);
        if (ObjectUtils.isEmpty(projectPatentExpand)) {
            throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "修改失败，项目信息不存在！");
        }
        projectPatentExpand.setProjectAssist(assistId);
        String currentTime = TimeUtils.getDate(TimeFormatConstants.YYYY_MM_DD_HH_MM_SS);
        User currentUser = (User) ThreadlocalUtils.getCache(ThreadLocalConstants.USER_INFO);
        projectPatentExpand.setUpdateTime(currentTime);
        projectPatentExpand.setUpdateUser(currentUser.getId());
        projectPatentExpandDao.updateById(projectPatentExpand);
    }


    /**
     * 补全数据
     *
     * @param originList 原始数据
     * @param startNum   起始值
     * @return 补全后数据
     */
    private List<Map<String, Object>> completeResult(List<PatentProjectDto> originList, int startNum,String currentUserId,boolean superPermission) {
        List<Map<String, Object>> resultList = new ArrayList<>(originList.size());
        Map<String, Map<String, String>> userMap = userDao.getUserMap();
        Map<String, Map<String, String>> departmentMap = patentDepartmentDao.getDepartmentMap();
        User currentUser = (User) ThreadlocalUtils.getCache(ThreadLocalConstants.USER_INFO);
        int sort = startNum + 1;
        for (PatentProjectDto project : originList) {
            Map<String, Object> map = ObjectUtils.object2Map(project);
            map.put("sort", sort);
            map.put("projectManagerName", userMap.containsKey(project.getProjectManager()) ? userMap.get(project.getProjectManager()).get("name") : "");
            map.put("projectLevelName", ProjectLevelEnum.getNameByValue(project.getProjectLevel()));
//            map.put("projectSourceName", ProjectSourceEnum.getNameByValue(project.getProjectSource()));
            Map<String, String> departmentInfo = departmentMap.containsKey(project.getDepartment()) ? departmentMap.get(project.getDepartment()) : new HashMap<>();
            map.put("projectDepartmentName", departmentInfo.get("name"));
            map.put("projectTypeName", project.getProjectType() == 1 ? "预研项目" : project.getProjectType() == 2 ? "新品开发" : project.getProjectType() == 3 ? "其他" : "未知类型");
            map.put("statusName", DifficultyStatusEnum.getNameByValue(project.getStatus()));
            map.put("stageName", ProjectPatentStageEnum.getNameByValue(project.getStage()));
            map.put("riskName", PatentRiskTypeEnum.getNameByValue(project.getRiskStatus()));
            List<String> assistNameList = new ArrayList<>();
            if (!StringUtils.isEmpty(project.getProjectAssist())) {
                List<String> assistList = Arrays.asList(project.getProjectAssist().split(","));
                for (String assist : assistList) {
                    if (userMap.containsKey(assist)) {
                        assistNameList.add(userMap.get(assist).get("name"));
                    }
                }
            }
            map.put("assistName", StringUtils.strip(assistNameList.toString(), "[]").replaceAll(" +", ""));
            List<String> dutyUserList = StringUtils.isEmpty(departmentInfo.get("dutyUser")) ? new ArrayList<>() : Arrays.asList(departmentInfo.get("dutyUser").split(","));
            boolean patentPermission = false;
            for (String user : dutyUserList) {
                if (StringUtils.equals(user, currentUser.getId())) {
                    patentPermission = true;
                }
            }
            map.put("patentPermission", patentPermission);
            map.put("managePermission", StringUtils.equals(project.getProjectManager(),currentUserId) || superPermission);
            resultList.add(map);
            sort++;
        }
        return resultList;
    }

    /**
     * 补全数据
     *
     * @param originList 原始数据
     * @param startNum   起始值
     * @return 补全后数据
     */
    private List<Map<String, Object>> completeRiskResult(List<PatentRisk> originList, int startNum) {
        List<Map<String, Object>> resultList = new ArrayList<>(originList.size());
        Map<String, Map<String, String>> userMap = userDao.getUserMap();
        int sort = startNum + 1;
        String currentIp = IPUtils.getCurrentIp();
        for (PatentRisk patentRisk : originList) {
            Map<String, Object> map = ObjectUtils.object2Map(patentRisk);
            map.put("sort", sort);
            map.put("createUserName", userMap.containsKey(patentRisk.getCreateUser()) ? userMap.get(patentRisk.getCreateUser()).get("name") : "");
            map.put("operateUserName", userMap.containsKey(patentRisk.getOperateUser()) ? userMap.get(patentRisk.getOperateUser()).get("name") : "");
            map.put("proposalNum", 2);
            Map<String, Object> fileMap = fileManageService.queryFileManageInfos(patentRisk.getId());
            if (fileMap.containsKey("39")) {
                map.put("pictureUrl", fileMap.get("39"));
            }
            if (fileMap.containsKey("40")) {
                List<Map<String, Object>> list = (List<Map<String, Object>>) fileMap.get("40");
                map.put("recordUrl", list.get(0).get("path"));
            }
            map.put("planSourceInfo", StringUtils.isEmpty(patentRisk.getPlanSourceInfo()) ? "-" : patentRisk.getPlanSourceInfo());
//            if (!StringUtils.isEmpty(patentRisk.getSearchRecord())) {
//               FileManage fileManage = fileManageDao.selectById(patentRisk.getSearchRecord());
//               map.put("recordUrl", fileManage.getFilePath().replace("upload", "http:\\\\" + currentIp + ":8090\\preview\\upload"));
//            }
            resultList.add(map);
            sort++;
        }
        return resultList;
    }


}
